const { parseRule } = require('./parser')
const cheerio = require('cheerio')
const _ = require('lodash')
const request = require('./request')
const qs = require('query-string')
const { getEncodeURI, decode } = require('./charset')

function parseSearch (source, doc) {
  const $ = cheerio.load(doc)
  const list = parseRule(source.ruleSearchList, $)

  const searchItemMap = {
    name: 'ruleSearchName',
    author: 'ruleSearchAuthor',
    kind: 'ruleSearchKind',
    lastChapter: 'ruleSearchLastChapter',
    introduce: 'ruleSearchIntroduce',
    coverUrl: 'ruleSearchCoverUrl',
    noteUrl: 'ruleSearchNoteUrl',
    infoInit: 'ruleBookInfoInit'
  }

  const searchItems = []

  list.each(function () {
    const item = {}
    Object.keys(searchItemMap).forEach(prop => {
      item[prop] = _.trim(parseRule(source[searchItemMap[prop]], $(this)))
    })
    searchItems.push(item)
  })

  return searchItems
}

async function downloadSearch (source, keyword, page = 1) {
  const [searchUrl, optionsUrl] = source.ruleSearchUrl.split('|')
  // eslint-disable-next-line no-unused-vars
  let options = {}
  if (optionsUrl) {
    options = qs.parse(optionsUrl)
  }
  let method = 'get'
  let url = ''
  let query = {}
  if (searchUrl.indexOf('@') !== -1) {
    method = 'post'
    const parseUrlObj = searchUrl.split('@')
    url = parseUrlObj[0]
    query = parseUrlObj[1]
    query = query.replace('searchPage', page)
    query = query.replace('searchKey', keyword)
    query = getEncodeURI(query, options.char)
  } else {
    method = 'get'
    url = searchUrl
    if (url.includes('searchKey=searchKey')) {
      url.replace('searchKey=searchKey', 'searchKey=' + keyword)
    } else {
      url = url.replace('searchKey', keyword)
    }
    url = url.replace('searchKey', keyword)
    url = getEncodeURI(url, options.char)
  }
  const result = await request[method](url, query, source, options.char === 'gbk')
  return result
}

module.exports = {
  parseSearch,
  downloadSearch
}
